package cn.globalph.housekeeper.data.retrofit
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

class HttpManager {
    companion object{
        @Volatile
        private var instance:HttpManager? = null

        fun getInstance():HttpManager{
            return instance?: synchronized(this){
                instance?:HttpManager().also { instance = it }
            }
        }
    }


    val api by lazy {
        create(HttpConstant.BASE_URL, Api::class.java)
    }

    private fun <T> create(baseUrl:String,c:Class<T>):T{
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(provideOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .build()
            .create(c)
    }

    private fun provideOkHttpClient():OkHttpClient{
        return OkHttpClient.Builder()
            .connectTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(20L,TimeUnit.SECONDS)
            .writeTimeout(20L,TimeUnit.SECONDS)
            .addInterceptor(HeaderInterceptor())
            .build()
    }
}